import time

import numpy as np
from keras import models, layers
from keras.datasets import imdb
from matplotlib import pyplot as plt

(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)


def vectorize_sequences(sequences, dimension=10000):
    results = np.zeros((len(sequences), dimension))

    for i, sequence in enumerate(sequences):
        results[i, sequence] = 1.

    return results

x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)

y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')


# 配置神经网络结构
model = models.Sequential()
# 配置全连接层 ： Dense(神经元个数,activation = '激活函数',
#                     kernel_regularizer = "正则化方式)
model.add(layers.Dense(2, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(2, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))


# 配置训练用的优化器（optimizer）、损失函数（loss）、准确率（metrics）等
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])


x_val = x_train[:10000]
pratial_x_train = x_train[10000:]

y_val = y_train[:10000]
pratial_y_train = y_train[10000:]

history = model.fit(pratial_x_train, pratial_y_train,epochs=20,batch_size=512,validation_data=(x_val,y_val))

# 查看history里的值（val_accuracy，val_loss，accuracy，loss）
# history.history

# 绘图
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(loss) + 1)

plt.plot(epochs, loss,'bo', label = 'Training loss')
plt.plot(epochs, val_loss,'b', label='Validation loss')
plt.title('Traing and valitdation loss')
plt.xlabel('Epochs')
plt.legend()
plt.show()